package com.jean.cameratest;

import android.content.Context;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.util.Log;
import android.view.Surface;
import android.view.TextureView;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created on 12/12/21.
 */
class Camera1 {
    private Context mContext;
    private Camera mCamera = null;
    private Camera.CameraInfo mInfo = new Camera.CameraInfo();
    private Camera.Parameters mParameters;

    private TextureView mTextureView;

    private MediaRecorder mMediaRecorder;

    public Camera1(Context context) {
        mContext = context;
    }

    public void setTextureView(TextureView view) {
        mTextureView = view;
    }

    private void config() {
        File file = new File(mContext.getExternalCacheDir(), "CameraRecorder.mp4");
        if (file.exists()) {
            file.delete();
        }

        mCamera.unlock();

        mMediaRecorder = new MediaRecorder();
        mMediaRecorder.setCamera(mCamera);
        mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
        mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
        mMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        mMediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        mMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);

        Surface surface = new Surface(mTextureView.getSurfaceTexture());
        mMediaRecorder.setPreviewDisplay(surface); //set preview
        mMediaRecorder.setOutputFile(file.getAbsolutePath());
        mMediaRecorder.setVideoEncodingBitRate(10000000);
        mMediaRecorder.setVideoFrameRate(30);
        mMediaRecorder.setVideoSize(640, 480);
    }

    private void start() {
        try {
            Log.i("CAMERA", "before prepare");
            mMediaRecorder.prepare();
            Log.i("CAMERA", "before start");
            mMediaRecorder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void open() {
        int number = Camera.getNumberOfCameras();
        if (number == 0) {
            return;
        }

        Camera.getCameraInfo(0, mInfo);
        mCamera = Camera.open(0);
        mParameters = mCamera.getParameters();
        List<Camera.Size> videoSizes = mParameters.getSupportedVideoSizes();
        if (videoSizes != null) {

        }

        config();

        start();
    }
}
